package com.elvish.efast.common.aspect;

import com.elvish.efast.common.anno.BuildTree;
import com.elvish.efast.common.entity.TreeData;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.nutz.lang.Lang;
import org.nutz.lang.Strings;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 构建树切面
 *
 * @author elvish
 * @date 2018/11/14 13:38
 * @blog oschina(https : / / my.oschina.net / xiaozhutefannao)
 */
@Component
@Aspect
@Slf4j
public class BuildTreeAspect {

    @Around("@annotation(buildTree)")
    public Object doAround(ProceedingJoinPoint pjp, BuildTree buildTree) {
        Object res = null;
        List<TreeData> root = Lists.newArrayList();
        try {
            res = pjp.proceed();
            List<TreeData> dataList = (List<TreeData>) res;
            if (!Lang.isEmpty(dataList)) {
                for (TreeData child : dataList) {
                    String pid = child.getPid();
                    // 一级
                    if (Strings.isBlank(pid) || "-1".equals(pid)) {
                        root.add(child);
                    } else {
                        // 一级以下
                        for (TreeData parent : dataList) {
                            String id = parent.getId();
                            if (pid.equals(id)) {
                                if (parent.getChildren() == null) {
                                    List<TreeData> children = Lists.newArrayList();
                                    parent.setChildren(children);
                                }
                                parent.getChildren().add(child);
                            }
                        }
                    }
                }
            }
            res = root;
        } catch (Throwable e) {
            log.error("构建树切面异常", e);
        }
        return res;
    }

}
